package com.dwxt.mall.controller;

import com.dwxt.common.annotation.ValidateFiled;
import com.dwxt.common.annotation.ValidateGroup;
import com.dwxt.common.base.BaseResult;
import com.dwxt.mall.entity.PayOrder;
import com.dwxt.mall.service.WXService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

@RequestMapping("/mall/wx")
@RestController
@Slf4j
public class WXPayController {

    @Autowired
    private WXService wxService;

    /**
     * showdoc
     * @catalog 商城/订单
     * @title 微信支付
     * @description 获取微信支付的必要参数并创建待支付订单
     * @url /mall/wx/createOrderWithWX
     * @param number 必选 int 购买数量
     * @param integral 必选 int 消耗积分
     * @param realPrice 必选 double 实际费用
     * @param productId 商城必选 int 产品id
     * @param addressId 商城必选 int 地址id
     * @param category 赛事必选 string 订单种类(race)
     * @param name 赛事必选 string 赛事名称
     * @return {"status":200,"msg":"SUCCESS","data":{}}
     */
    @RequestMapping("/createOrderWithWX")
    @ValidateGroup(fileds = {
            @ValidateFiled(index = 0,filedName = "number", notNull = true),
            @ValidateFiled(index = 0,filedName = "integral", notNull = true),
            @ValidateFiled(index = 0,filedName = "realPrice", notNull = true),
    })
    //赛事活动 category number integral realPrice name
    public BaseResult createOrderWithWX(PayOrder order, HttpServletRequest request) throws Exception {
        synchronized (WXPayController.class){
            //默认值 app支付  2 扫码支付 3 小程序支付
            return wxService.createOrderWithWX(order, request.getRemoteAddr(),request);
        }
    }

    /**
     * 微信支付回调接口
     */
    @RequestMapping("/callback")
    public void callback(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String resXml = "";
        try {
            resXml = getResXmlString(request);
            log.info("微信支付异步通知请求包: {}", resXml);
            String payBack = wxService.payBack(resXml);
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().write(payBack);
        } catch (Exception e) {
            log.error("微信支付回调通知失败", e);
            String result = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" +
                    "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().write(result);
        }
    }

    private String getResXmlString(HttpServletRequest request) throws IOException {
        InputStream is = request.getInputStream();
        //将InputStream转换成String
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        return sb.toString();
    }

}
